package com.shopping.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.common.utils.HttpUtils;
import com.shopping.common.utils.PageUtils;
import com.shopping.common.utils.Query;
import com.shopping.member.dao.MemberDao;
import com.shopping.member.dao.MemberLevelDao;
import com.shopping.member.entity.MemberEntity;
import com.shopping.member.entity.MemberLevelEntity;
import com.shopping.member.exception.PhoneExistException;
import com.shopping.member.exception.UsernameExistException;
import com.shopping.member.service.MemberService;
import com.shopping.member.vo.MemberLoginVo;
import com.shopping.member.vo.MemberRegisterVo;
import com.shopping.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao levelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 直接注册,非社交账号注册
     *
     * @param registerVo MemberRegisterVo
     */
    @Override
    public void register(MemberRegisterVo registerVo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //检查用户名和手机号是否存在
        checkUserName(registerVo.getUserName());
        checkPhone(registerVo.getPhone());
        //设置默认等级
        MemberLevelEntity levelEntity = levelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        entity.setUsername(registerVo.getUserName());
        entity.setMobile(registerVo.getPhone());
        //密码加密处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(registerVo.getPassword());
        entity.setPassword(encode);

        //保存
        memberDao.insert(entity);
    }


    /**
     * 检查注册时是否重名
     *
     * @param userName
     * @throws UsernameExistException
     */
    @Override
    public void checkUserName(String userName) throws UsernameExistException {
        MemberDao memberDao = this.baseMapper;
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userName);
        Integer username = memberDao.selectCount(wrapper);
        if (username > 0) {
            throw new UsernameExistException();
        }
    }

    /**
     * 检查注册时该号码是否注册过
     *
     * @param phone
     */
    @Override
    public void checkPhone(String phone) {
        MemberDao memberDao = this.baseMapper;
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        Integer mobile = memberDao.selectCount(wrapper);
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {
        String account = loginVo.getAccount();
        String password = loginVo.getPassword();
        MemberDao memberDao = this.baseMapper;
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", account).or().eq("mobile", account);
        MemberEntity memberEntity = memberDao.selectOne(wrapper);
        if (memberEntity == null) {
            return null;
        } else {
            //匹配密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, memberEntity.getPassword());
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    /**
     * 社交登陆
     * 判断用户是否存在,存在就登陆否则就注册
     *
     * @param userVo SocialUserVo
     * @return
     */
    @Override
    public MemberEntity oauthLogin(SocialUserVo userVo) {
        String uid = userVo.getUid();
        System.out.println("uid = " + uid);
        String accessToken = userVo.getAccessToken();
        System.out.println("accessToken = " + accessToken);
        MemberDao memberDao = this.baseMapper;
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("weibo_social_uid", uid);
        MemberEntity memberEntity = memberDao.selectOne(wrapper);
        //已经注册过的就更新一下数据
        if (memberEntity != null) {
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(memberEntity.getAccessToken());
            update.setExpiresIn(memberEntity.getExpiresIn());
            //更新操作
            memberDao.updateById(update);
            //重置下令牌以及过过期时间
            memberEntity.setAccessToken(accessToken);
            memberEntity.setExpiresIn(userVo.getExpiresIn());
            return memberEntity;
        }
        //没有注册过
        MemberEntity register = new MemberEntity();
        //try里的东西可以拿不到,但不能影响插入数据
        try {
            HashMap<String, String> queries = new HashMap<>(16);
            queries.put("access_token", accessToken);
            queries.put("uid", uid);
            HttpResponse get = HttpUtils.doGet(
                    "http://api.weibo.com",
                    "/2/users/show.json",
                    "get",
                    new HashMap<>(),
                    queries);
            if (get.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(get.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                //设置下基本注册信息
                register.setNickname(name);
                Integer sex = "m".equals(gender) ? 1 : 0;
                register.setGender(sex);
                System.out.println("jsonObject = " + jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            register.setNickname("我还没有改名字");
        }
        register.setWeiboSocialUid(uid);
        register.setAccessToken(accessToken);
        register.setExpiresIn(userVo.getExpiresIn());
        memberDao.insert(register);
        return register;
    }


}